package me.seu.demo.service.emqx.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Topic 正则匹配
 *
 * @author liangfeihu
 * @since 2021/11/9 13:36
 */
public class MqttTopicMatcher {

    private final String topic;
    private final Pattern topicRegex;

    public MqttTopicMatcher(String topic) {
        if (topic == null) {
            throw new NullPointerException("topic");
        }
        this.topic = topic;
        this.topicRegex = Pattern.compile(topic.replace("+", "[^/]+").replace("#", ".+") + "$");
    }

    public String getTopic() {
        return topic;
    }

    public boolean matches(String topic) {
        return this.topicRegex.matcher(topic).matches();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        MqttTopicMatcher that = (MqttTopicMatcher) o;

        return topic.equals(that.topic);
    }

    @Override
    public int hashCode() {
        return topic.hashCode();
    }

    public static void main(String[] args) {
        final String TOPIC = "/sys/property/+/all/#";
        String testTopic = "/sys/property/device1/all/a/b/c";

        String pattern = TOPIC.replace("+", "[^/]+").replace("#", ".+") + "$";
        System.out.println(pattern);

        Pattern compile = Pattern.compile(pattern);
        Matcher patternMatcher = compile.matcher(testTopic);
        boolean matches = patternMatcher.matches();
        System.out.println(matches);

        while (patternMatcher.find()){
            System.out.println(patternMatcher.group());
        }

        MqttTopicMatcher matcher = new MqttTopicMatcher(TOPIC);
        boolean matchFlag = matcher.matches(testTopic);
        System.out.println("matchFlag=" + matchFlag);

    }

}
